package com.dd.ent.car;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.interf.BaseViewInterface;
import com.dd.ent.car.common.interf.OnTabReselectListener;
import com.dd.ent.car.common.player.XLAlarmDialog;
import com.dd.ent.car.common.xrichtext.ui.NewActivity;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.BaseActivity;
import com.dd.ent.car.ui.MainTab;
import com.dd.ent.car.ui.camera.SendSmallVideoActivity;
import com.dd.ent.car.ui.camera.local.SelectVideoActivity;
import com.dd.ent.car.ui.more.MoreWindow;
import com.dd.ent.car.ui.user.LoginActivity;
import com.dd.ent.car.ui.widget.CircleImageView;
import com.dd.ent.car.ui.widget.MyFragmentTabHost;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.ServiceHandler;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.db.DbResult;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import mabeijianxi.camera.MediaRecorderActivity;
import mabeijianxi.camera.model.MediaRecorderConfig;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements
        TabHost.OnTabChangeListener, BaseViewInterface,
        View.OnTouchListener {
    private final static String TAG = "MainActivity";
    private static final int PICK_PHOTO = 1;

    @ViewInject(R.id.myFragmentTabHost)
    MyFragmentTabHost mTabHost;

    @ViewInject(R.id.drawer_layout)
    private FrameLayout mDrawerLayout;

    @ViewInject(R.id.img_thumb)
    private CircleImageView imgThumb;
    @ViewInject(R.id.tv_title)
    private TextView tvTitle;

    @ViewInject(R.id.fra_titleBar)
    private FrameLayout fraTitleBar;

    @ViewInject(R.id.realtabcontent)
    private FrameLayout realtabcontent;

    @ViewInject(R.id.tab_bottom)
    private FrameLayout tabBottom;

    @ViewInject(R.id.quick_option_iv)
    private ImageView quickOptionIv;
    private boolean canScroll = true;

    private ArrayList<String> imagePaths = new ArrayList<>();
    private MoreWindow mMoreWindow;
    @Inject
    private UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initLogin();
    }

    private void initLogin() {
        userService.loginFromDb();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTabChanged(String tabId) {
        MLog.debug(TAG, "onTabChanged tabId=" + tabId);
        if (tabId.equals(getString(MainTab.Video.getResName()))) {
            canScroll = true;
        } else {
            canScroll = false;
        }
        tvTitle.setText(tabId);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        super.onTouchEvent(event);
        boolean consumed = false;
        // use getTabHost().getCurrentTabView to decide if the current tab is
        // touched again
        if (event.getAction() == MotionEvent.ACTION_DOWN
                && v.equals(mTabHost.getCurrentTabView())) {
            // use getTabHost().getCurrentView() to get a handle to the view
            // which is displayed in the tab - and to get this views context
            Fragment currentFragment = getCurrentFragment();
            if (currentFragment != null
                    && currentFragment instanceof OnTabReselectListener) {
                OnTabReselectListener listener = (OnTabReselectListener) currentFragment;
                listener.onTabReselect();
                consumed = true;
            }
        }
        return consumed;
    }

    private Fragment getCurrentFragment() {
        return getSupportFragmentManager().findFragmentByTag(
                mTabHost.getCurrentTabTag());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void initView() {
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        if (android.os.Build.VERSION.SDK_INT > 10) {
            mTabHost.getTabWidget().setShowDividers(0);
        }
        initTabs();
        // 中间按键图片触发
        mTabHost.setCurrentTab(0);
        mTabHost.setOnTabChangedListener(this);
        quickOptionIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMoreMenuWindow(v);
            }
        });
        //  initEvents();

    }

    @ServiceHandler("query_db_user")
    public void queryDbUserResponse(DbResult dbResult) {
        if (dbResult == null) {
            return;
        }
        List<User> users = (List<User>) dbResult.data;
        if (users != null && users.size() != 0) {
            User user = users.get(0);
            if (TextUtils.equals(user.getUid(), "a62682c9-d831-41d8" +
                    "-91d1-64bfb77450a1") ||
                    TextUtils.equals(user.getUid(), "05d4f874-bddf-49e1-8f49-2b7e7f7728c3")) {
                quickOptionIv.setVisibility(View.VISIBLE);
            } else {
                quickOptionIv.setVisibility(View.GONE);
            }
        }
    }

    @UIHandler(UIConfig.PHONE_NUMBER_LOGIN_SUCCESS)
    public void phoneNumberRegisteSuccessResponse(User user) {
        if (user != null) {
            if (TextUtils.equals(user.getUid(), "a62682c9-d831-41d8" +
                    "-91d1-64bfb77450a1") ||
                    TextUtils.equals(user.getUid(), "05d4f874-bddf-49e1-8f49-2b7e7f7728c3")) {
                quickOptionIv.setVisibility(View.VISIBLE);
            } else {
                quickOptionIv.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    public void initData() {

    }

    @SuppressWarnings("deprecation")
    private void initTabs() {
        MainTab[] tabs = MainTab.values();
        int size = tabs.length;
        for (int i = 0; i < size; i++) {
            MainTab mainTab = tabs[i];
            TabHost.TabSpec tab = mTabHost.newTabSpec(getString(mainTab.getResName()));
            View indicator = View.inflate(this, R.layout.tab_indicator, null);
            TextView title = (TextView) indicator.findViewById(R.id.tab_title);
            ImageView icon = (ImageView) indicator.findViewById(R.id.iv_icon);

            Drawable drawable = this.getResources().getDrawable(mainTab.getResIcon());
            icon.setImageDrawable(drawable);
            //title.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            if (i == 1) {
                indicator.setVisibility(View.INVISIBLE);
                mTabHost.setNoTabChangedTag(getString(mainTab.getResName()));
            }
            title.setText(getString(mainTab.getResName()));
            tab.setIndicator(indicator);
            tab.setContent(new TabHost.TabContentFactory() {

                @Override
                public View createTabContent(String tag) {
                    return new View(MainActivity.this);
                }
            });
            mTabHost.addTab(tab, mainTab.getClz(), null);
            mTabHost.getTabWidget().getChildAt(i).setOnTouchListener(this);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (canScroll) {
            dispathTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isDown = false;
    private boolean isUp = false;
    private boolean mIsAnim = false;
    private boolean mIsTitleHide = false;
    private float lastX = 0;
    private float lastY = 0;

    private boolean dispathTouchEvent(MotionEvent event) {
        if (mIsAnim) {
            return false;
        }
        final int action = event.getAction();

        float x = event.getX();
        float y = event.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                lastY = y;
                lastX = x;
                return false;
            case MotionEvent.ACTION_MOVE:
                float dY = Math.abs(y - lastY);
                float dX = Math.abs(x - lastX);
                boolean down = y > lastY ? true : false;
                lastY = y;
                lastX = x;
                isUp = dX < 8 && dY > 8 && !mIsTitleHide && !down;
                isDown = dX < 8 && dY > 8 && mIsTitleHide && down;

                if (isUp) {
                    doHiddenAnimator();
                } else if (isDown) {
                    doShowAnimator();
                } else {
                    return false;
                }
                mIsTitleHide = !mIsTitleHide;

                break;
            default:
                return false;
        }
        return false;

    }

    private void doHiddenAnimator() {
        AnimatorSet set = new AnimatorSet();
        final android.animation.ObjectAnimator tranTitleBarY;
        android.animation.ObjectAnimator tranContentY;
        android.animation.ObjectAnimator tranBottomY;
        tranTitleBarY = android.animation.ObjectAnimator
                .ofFloat(fraTitleBar, "translationY", 0, -fraTitleBar.getHeight());//Y轴平移旋转
        tranContentY = android.animation.ObjectAnimator
                .ofFloat(realtabcontent, "translationY", 0, -fraTitleBar.getHeight());//Y轴平移旋转
        tranBottomY = android.animation.ObjectAnimator
                .ofFloat(tabBottom, "translationY", 0, fraTitleBar.getHeight());//Y轴平移旋转

        set.playTogether(tranTitleBarY, tranContentY, tranBottomY);
        set.setDuration(300);
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // Peer.notifyUI(UIConfig.CHANGE_TITLE_BACKGROUND, R.color.blue_600, true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        set.start();


    }

    private void doShowAnimator() {
        AnimatorSet set = new AnimatorSet();
        android.animation.ObjectAnimator tranTitleBarY;
        android.animation.ObjectAnimator tranContentY;
        android.animation.ObjectAnimator tranBottomY;
        tranTitleBarY = android.animation.ObjectAnimator
                .ofFloat(fraTitleBar, "translationY", -fraTitleBar.getHeight(), 0);//Y轴平移旋转
        tranContentY = android.animation.ObjectAnimator
                .ofFloat(realtabcontent, "translationY", -fraTitleBar.getHeight(), 0);//Y轴平移旋转
        tranBottomY = android.animation.ObjectAnimator
                .ofFloat(tabBottom, "translationY", fraTitleBar.getHeight(), 0);//Y轴平移旋转

        set.playTogether(tranTitleBarY, tranContentY, tranBottomY);
        set.setDuration(300);
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // Peer.notifyUI(UIConfig.CHANGE_TITLE_BACKGROUND, R.color.day_windows_bg, false);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        set.start();

    }

    @Override
    public void onBackPressed() {
        XLAlarmDialog xlAlarmDialog = new XLAlarmDialog(this);
        xlAlarmDialog.setTitle("车友圈");
        xlAlarmDialog.setContent("确定退出？");
        xlAlarmDialog.setOnClickConfirmButtonListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppContext.getInstance().killself();
            }
        });
        xlAlarmDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showMoreMenuWindow(View view) {
        if (null == mMoreWindow) {
            mMoreWindow = new MoreWindow(this);
            mMoreWindow.init();
        }
        mMoreWindow.setMoreMenuListener(new MoreWindow.MoreMenuListener() {
            @Override
            public void btnForumClick(View view) {
                if (userService.isLogin()) {
                    NewActivity.startSelf(MainActivity.this);
                } else {
                    LoginActivity.startActivity(MainActivity.this);
                }
            }

            @Override
            public void btnLocalVideoClick(View view) {
                if (userService.isLogin()) {
                    SelectVideoActivity.startSelf(MainActivity.this);
                } else {
                    LoginActivity.startActivity(MainActivity.this);
                }
            }

            @Override
            public void btnCameraClick(View view) {
                if (userService.isLogin()) {
                    startSmallRecord();
                } else {
                    LoginActivity.startActivity(MainActivity.this);
                }
            }
        });
        mMoreWindow.showMoreWindow(view);
    }

    private void startSmallRecord() {
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .doH264Compress(false)
                .smallVideoWidth(480)
                .smallVideoHeight(360)
                .recordTimeMax(60 * 1000)
                .maxFrameRate(20)
                .minFrameRate(8)
                .captureThumbnailsTime(1)
                .recordTimeMin((int) (5 * 1000))
                .build();
        MediaRecorderActivity
                .goSmallVideoRecorder(this, SendSmallVideoActivity.class.getName(), config);
    }

}
